<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\Pay;
use app\common\Platform;
use app\common\Sms;
use app\common\UserService;
use app\model\Goods;
use app\model\Help;
use app\model\Shop;
use app\model\Super;
use app\model\SuperSpec;
use app\model\User;
use app\model\UserBank;
use app\model\UserCollect;
use app\model\UserGoodsDevoteLog;
use app\model\UserGoodsQuotaLog;
use app\model\UserLayer;
use app\model\UserMoneyLog;
use app\model\UserRechargeLog;
use app\model\UserScoreLog;
use app\model\UserShopQuotaLog;
use app\model\UserSuperQuotaLog;
use app\model\UserWithdraw;
use app\tool\Random;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use Exception;
use GuzzleHttp\Client;
use thans\jwt\facade\JWTAuth;
use think\db\Query;
use think\facade\Db;
use think\facade\Validate;

class UserController extends BaseController
{
	function login()
	{
		$logintype = $this->request->post('logintype'); #登陆方式:mobile  password
		$mobile = $this->request->post('mobile');
		$password = $this->request->post('password');
		$captcha = $this->request->post('captcha');
		$wechatcode = $this->request->post('wechatcode');
        if ( $this->request->header('Client') == 'wechatmini' && empty($wechatcode)){
            $this->writeJson(0, '获取小程序OPENID失败');
        }
		$user = User::getByMobile($mobile);
		if (!$mobile || !$user) {
			$this->writeJson(0, '该号码未注册');
		}
		switch ($logintype) {
			case 'mobile':
				$captchaResult = Sms::check($mobile, $captcha, 'login');
				if (!$captchaResult) {
					$this->writeJson(0, '验证码错误');
				}
				break;
			case 'password':
				if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
					$this->writeJson(0, '密码错误');
				}
				break;
			default:
				$this->writeJson(0, '登录类型错误');
		}
		$ip = request()->ip();
		$time = time();
		if (!$user) {
			$this->writeJson(0, '账号不存在');
		} else {
			if ($user->status == 'hidden') {
				$this->writeJson(0, '账号被封禁');
			}
			if (!empty($wechatcode)) {
				try {
					$openid = Platform::getWechatMiniOpenid($wechatcode);
				} catch (\Throwable) {
					$this->writeJson(0, '微信登录失败');
				}
				$user->openid = $openid;
			}
			$user->prevtime = $user->logintime;
			$user->logintime = $time;
			$user->loginip = $ip;
			$user->save();
			$token = JWTAuth::builder(['user_id' => $user->id]);
		}
		$this->writeJson(1, '登录成功', '', 'json', ['Authorization' => 'Bearer ' . $token]);
	}
	
	function register()
	{
		$mobile = $this->request->post('mobile');
		$captcha = $this->request->post('captcha');
		$password = $this->request->post('password');
		$invitecode = $this->request->post('invitecode');
		$wechatcode = $this->request->post('wechatcode');
        if ( $this->request->header('Client') == 'wechatmini' && empty($wechatcode)){
            $this->writeJson(0, '获取小程序OPENID失败');
        }
		if (empty($invitecode)) {
			$this->writeJson(0, '邀请码不能为空');
		}
		
		if ($mobile && User::getByMobile($mobile)) {
			$this->writeJson(0, '手机号已存在');
		}
		
		$captchaResult = Sms::check($mobile, $captcha, 'register');
		if (!$captchaResult) {
			$this->writeJson(0, '验证码错误');
		}
		
		
		// 启动事务
		Db::startTrans();
		try {
			$parent = User::getByInvitecode($invitecode); //父级
			if (!$parent) {
				throw new Exception('邀请码错误');
			}
			
			$ip = request()->ip();
			$time = time();
			$data = [
				'password' => $password,
				'mobile' => $mobile,
				'level' => 1,
				'score' => 0,
				'avatar' => '/assets/img/avatar.png',
				'pid' => $parent->id
			];
			
			
			$nickname = '用户' . Random::alnum();
			
			
			$params = array_merge($data, [
				'nickname' => $nickname,
				'salt' => Random::alnum(),
				'jointime' => $time,
				'joinip' => $ip,
				'logintime' => $time,
				'loginip' => $ip,
				'prevtime' => $time,
				'status' => 'normal',
			]);
			do {
				$invitecode = Random::alnum();
			} while (User::where(['invitecode' => $invitecode])->find());
			$params['invitecode'] = $invitecode;
			$params['password'] = $this->getEncryptPassword($password, $params['salt']);


			if (!empty($wechatcode)) {
				$openid = Platform::getWechatMiniOpenid($wechatcode);
				$params['openid'] = $openid;
			}
			
			$user = User::create($params);
			//增加直推关系
			$position = UserLayer::where('user_id', $parent->id)->select();
			$data['user_id'] = $user->id;
			$data['pid'] = $parent->id;
			$data['level'] = 1;
			UserLayer::create($data);
			if (!$position->isEmpty()) {
				foreach ($position as $v) {
					$data = [
						'user_id' => $user->id,
						'pid' => $v->pid,
						'level' => $v->level + 1,
					];
					UserLayer::create($data);
				}
			}
			$token = JWTAuth::builder(['user_id' => $user->id]);
			// 提交事务
			Db::commit();
		} catch (\Throwable $e) {
			// 回滚事务
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		
		$this->writeJson(1, '注册成功', '', 'json', ['Authorization' => 'Bearer ' . $token]);
	}
	
	#修改手机号
	function changeMobile()
	{
		$mobile = $this->request->post('mobile');
		$captcha = $this->request->post('captcha');
		if (empty($mobile) || empty($captcha)) {
			$this->writeJson(0, '手机号或验证码不能为空');
		}
		$captchaResult = Sms::check($mobile, $captcha, 'changemobile');
		if (!$captchaResult) {
			$this->writeJson(0, '验证码错误');
		}
		$user = User::findOrFail($this->user_id);
		$user->mobile = $mobile;
		$user->save();
		
		$this->writeJson(1, '绑定成功');
	}
	
	
	#积分记录
	function userScore()
	{
		$status = $this->request->get('status/d'); // 0全部 1支出 2收入
		$rows = UserScoreLog::where(['user_id' => $this->user_id])->when(!empty($status), function (Query $query) use ($status) {
			if ($status == 1) {
				$query->where('score', '<=', 0);
			} else {
				$query->where('score', '>=', 0);
			}
		})->filter(function ($data) {
			if ($data->score > 0) {
				$data->score = '+' . $data->score;
			}
		})->order(['id' => 'desc'])->paginate()->items();
		$this->writeJson($rows);
	}
	
	
	function getUserInfo()
	{

		$row = User::with(['shop'])->findOrFail($this->user_id);
		$this->writeJson($row);
	}
	
	#充值余额
	function recharge()
	{
		$amount = $this->request->post('amount/f');
		$pay_type = $this->request->post('pay_type/d');
		$row = User::findOrFail($this->user_id);
		if (!$row->shop) {
			$this->writeJson(0, '请先成为商户');
		}
		$order_sn = Random::ordersn();
		$user = User::findOrFail($this->user_id);

		UserRechargeLog::create([
			'user_id' => $this->user_id,
			'amount' => $amount,
			'pay_type' => $pay_type,
			'order_sn' => $order_sn,
            'pay_source'=> request()->header('Client')
		]);
		try {
			$ret = Pay::pay($pay_type, $amount, $order_sn, '余额充值', 'recharge', $user->openid);
		} catch (\Throwable $e) {
			$this->writeJson(0, $e->getMessage());
		}
		$this->writeJson($ret);
	}
	
	/**
	 * 编辑个人信息
	 * @return void
	 */
	function userEdit()
	{
		$avatar = $this->request->post('avatar');
		$nickname = $this->request->post('nickname');
		$birthday = $this->request->post('birthday');
		$gender = $this->request->post('gender/d');//性别:1=男,2=女
		$user = User::findOrFail($this->user_id);
		if (!empty($avatar)) {
			$user->avatar = $avatar;
		}
		if (!empty($nickname)) {
			$user->nickname = $nickname;
		}
		if (!empty($birthday)) {
			$user->birthday = $birthday;
		}
		if (!empty($gender)) {
			$user->gender = $gender;
		}
		Db::startTrans();
		try {
			$user->save();
			// 提交事务
			Db::commit();
		} catch (\Throwable $e) {
			// 回滚事务
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		$this->writeJson();
	}
	
	
	function logoff()
	{
		$user = User::findOrFail($this->user_id);
		$user->delete();
		$this->writeJson();
	}
	
	/**
	 * 重置密码
	 * @return void
	 */
	function resetpwd()
	{
		$mobile = $this->request->post("mobile");
		$newpassword = $this->request->post("newpassword");
		$confirm_password = $this->request->post("confirm_password");
		$captcha = $this->request->post("captcha");
		if (!Validate::is($mobile, 'mobile')) {
			$this->writeJson(0, '手机号格式错误');
		}
		if ($newpassword != $confirm_password) {
			$this->writeJson(0, '确认密码不一致');
		}
		if (!Validate::is($newpassword, '\S{8,30}')) {
			$this->writeJson(0, '新密码密码必须8-30个字符');
		}
		$user = User::getByMobile($mobile);
		if (!$user) {
			$this->writeJson(0, '手机号未注册');
		}
		$ret = Sms::check($mobile, $captcha, 'changepwd');
		if (!$ret) {
			$this->writeJson(0, '验证码错误');
		}
		$salt = Random::alnum();
		$newpassword = $this->getEncryptPassword($newpassword, $salt);
		$user->password = $newpassword;
		$user->salt = $salt;
		$user->loginfailure = 0;
		$user->save();
		$this->writeJson();
	}
	
	#精品区分红额度
	function getUserGoodsQuotaList()
	{
		$status = $this->request->get('status/d');#0全部 1收入 2支出
		$rows = UserGoodsQuotaLog::where('user_id', $this->user_id)
			->when(!empty($status), function (Query $query) use ($status) {
				if ($status == 1) {
					$query->where('goods_quota', '>', 0);
				} else {
					$query->where('goods_quota', '<', 0);
				}
			})
			->filter(function ($data) {
				if ($data->goods_quota > 0) {
					$data->goods_quota = '+' . $data->goods_quota;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#优选区分红额度
	function getUserSuperQuotaList()
	{
		$status = $this->request->get('status/d');#0全部 1收入 2支出
		$rows = UserSuperQuotaLog::where('user_id', $this->user_id)
			->when(!empty($status), function (Query $query) use ($status) {
				if ($status == 1) {
					$query->where('super_quota', '>', 0);
				} else {
					$query->where('super_quota', '<', 0);
				}
			})
			->filter(function ($data) {
				if ($data->super_quota > 0) {
					$data->super_quota = '+' . $data->super_quota;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#商家分红额度
	function getUserShopQuotaList()
	{
		$status = $this->request->get('status/d');#0全部 1收入 2支出
		$rows = UserShopQuotaLog::where('user_id', $this->user_id)
			->when(!empty($status), function (Query $query) use ($status) {
				if ($status == 1) {
					$query->where('shop_quota', '>', 0);
				} else {
					$query->where('shop_quota', '<', 0);
				}
			})
			->filter(function ($data) {
				if ($data->shop_quota > 0) {
					$data->shop_quota = '+' . $data->shop_quota;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	
	#我的贡献值
	function getUserGoodsDevoteList()
	{
		$status = $this->request->get('status/d');#0全部 1收入 2支出
		$rows = UserGoodsDevoteLog::where('user_id', $this->user_id)
			->when(!empty($status), function (Query $query) use ($status) {
				if ($status == 1) {
					$query->where('goods_devote', '>', 0);
				} else {
					$query->where('goods_devote', '<', 0);
				}
			})
			->filter(function ($data) {
				if ($data->goods_devote > 0) {
					$data->goods_devote = '+' . $data->goods_devote;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#余额记录
	function getUserMoneyList()
	{
		$status = $this->request->get('status/d');#0全部 1收入 2支出
		$rows = UserMoneyLog::where('user_id', $this->user_id)
			->when(!empty($status), function (Query $query) use ($status) {
				if ($status == 1) {
					$query->where('money', '>', 0);
				} else {
					$query->where('money', '<', 0);
				}
			})
			->filter(function ($data) {
				if ($data->money > 0) {
					$data->money = '+' . $data->money;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#分销中心
	function team()
	{
		$user_ids = UserLayer::where(['pid' => $this->user_id])->column('user_id');
		$rows = User::whereIn('id', $user_ids)->select();
		$user = User::find($this->user_id);
		$this->writeJson(['list' => $rows, 'count' => $rows->count(), 'goods_team_devote' => $user->goods_team_devote]);
	}
	
	
	#提现
	function withdraw()
	{
		
		$type = $this->request->post('type/d');
		$bank_id = $this->request->post('bank_id/d');
		$amount = $this->request->post('amount');
		
		$ali_account = $this->request->post('ali_account');
		$ali_name = $this->request->post('ali_name');
		$ali_mobile = $this->request->post('ali_mobile');
		$idcard = $this->request->post('idcard');
		if ($amount < 100) {
			$this->writeJson(0, '提现金额不能小于100元');
		}
		$rate = 0.06;
		$fee = bcmul((string)$amount, (string)$rate, 2);
		if ($fee < 0.01) {
			$fee = 0.01;
		}
		$real_amount = bcsub($amount, (string)$fee, 2);
		try {
			UserService::changeUserMoney(-$amount, $this->user_id, '提现至' . ($type == 1 ? '银行卡' : '支付宝'));
			if ($type == 1) {
				$bank = UserBank::findOrFail($bank_id);
				$data = [
					'type' => $type,
					'user_id' => $this->user_id,
					'bank_id' => $bank->id,
					'amount' => $amount,
					'order_sn' => Random::ordersn(),
					'real_amount' => $real_amount,
					'name' => $bank->name,
					'idcard' => $bank->idcard,
					'account' => $bank->account,
					'bank' => $bank->bank,
					'bank_name' => $bank->bank_name,
					'mobile' => $bank->mobile,
					'fee' => $fee,
				];
			} else {
				$data = [
					'type' => $type,
					'user_id' => $this->user_id,
					'amount' => $amount,
					'order_sn' => Random::ordersn(),
					'real_amount' => $real_amount,
					'fee' => $fee,
					'ali_account' => $ali_account,
					'ali_name' => $ali_name,
					'ali_mobile' => $ali_mobile,
					'idcard' => $idcard,
				];
			}
			UserWithdraw::create($data);
		} catch (\Throwable $e) {
			$this->writeJson(0, $e->getMessage());
		}
		$this->writeJson();
	}
	
	#提现列表
	function withdrawList()
	{
		$rows = UserWithdraw::where(['user_id' => $this->user_id])
			->order(['id' => 'desc'])->paginate()->items();
		$this->writeJson($rows);
	}
	
	#转赠金钱
	function giveMoney()
	{
		$to_user_id = $this->request->post('to_user_id/d');
		$amount = $this->request->post('amount');
		$toUser = User::find($to_user_id);
		if (!$toUser) {
			$this->writeJson(0, '用户不存在');
		}
        $this->writeJson('此功能暂停使用');
		try {
			UserService::changeUserMoney(-$amount, $this->user_id, '转赠用户ID:' . $to_user_id);
			UserService::changeUserMoney($amount, $to_user_id, '被赠送来源用户ID:' . $this->user_id);
		} catch (\Throwable $e) {
			$this->writeJson(0, $e->getMessage());
		}
		$this->writeJson();
	}
	
	#邀请码
	function getQRCode()
	{
		$client = new Client();
		$user = User::findOrFail($this->user_id);
		$origin = $this->request->header('Client');
		if ($origin == 'app') {
			$writer = new PngWriter();

			$qrCode = QrCode::create('https://0307h5.62.nantaihu1.top/#/pages/login/register/register?invitecode='.$user->invitecode)
				->setSize(100)      //大小
				->setMargin(0)             //边距
				->setForegroundColor(new Color(0, 0, 0))        //前景色
				->setBackgroundColor(new Color(255, 255, 255));       //背景色
			$result = $writer->write($qrCode)->getDataUri();
		} else {
			$access_token = Platform::getWechatMiniToken();
			$wxacode = $client->post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token", [
				'body' => json_encode([
					'page' => "pages/login/register/register",
					'scene' => "{$user->invitecode}",
					'check_path' => !env('APP_DEBUG'),
					'env_version' => env('APP_DEBUG', true) ? 'trial' : 'release'
				])
			]);
			$result = 'data:image/png;base64,' . base64_encode($wxacode->getBody()->getContents());
		}
		$this->writeJson($result);
	}
	
	#我的收藏
	function getCollectList()
	{
		$type = $this->request->get('type/d'); #1精选区 2优选区 3门店
		
		$ids = UserCollect::where(['user_id' => $this->user_id])
			->when(!empty($type), function (Query $query) use ($type) {
				$query->where('type', $type);
			}, function () {
				$this->writeJson(0, '参数错误');
			})
			->filter(function ($data) {
			
			})
			->order(['id' => 'desc'])
			->paginate()
			->column('pro_id');
		if ($type == 1){
			$rows = Goods::order(['id' => 'desc'])
				->with(['spec'])
				->whereIn('id',$ids)
				->select();
			$this->writeJson($rows);
		}
		if ($type == 2){
			$rows = Super::whereIn('id',$ids)
				->filter(function ($data){
					$data->spec = SuperSpec::where(['super_id'=>$data->id])->order(['price'=>'asc'])->find();
				})
				->select();
			$this->writeJson($rows);
		}
		if ($type == 3){
			$rows = Shop::where(['status' => 2])->whereIn('id',$ids)
				->select();
			$this->writeJson($rows);
		}
	}
	
	#帮助中心
	function getHelpList()
	{
		$rows = Help::order(['weigh' => 'desc'])->select();
		$this->writeJson($rows);
	}
	
	#设置交易密码
	function setShopPassword()
	{
		$password = $this->request->post('password');
		if (empty($password)) {
			$this->writeJson(0, '密码不能为空');
		}
		$user = User::findOrFail($this->user_id);
		$user->shop->password = md5($password);
		$user->together(['shop'])->save();
		$this->writeJson();
	}
	
	#推广员
	function getShopTeam()
	{
		$user = User::findOrFail($this->user_id);
		$rows = Shop::where(['pid' => $this->user_id, 'status' => 2])->paginate()->items();
		$this->writeJson(['list' => $rows, 'invitecode' => $user->invitecode]);
	}
	
	
}
